<?php
/**
 * Class InvestService
 */
class InvestService extends BaseService
{

    private static $self           =   NULL;
    private $mInvest                =   NULL;
    private $mDealRecord            =   NULL;
    private $mUser = NULL;
    private $mUserAward = NULL;
    private $mItem= NULL;
    private $mUserTicket= NULL;
    private $mExperItem= NULL;
    private $mExperRecord= NULL;
    private $mUserFund= NULL;
    private $mInvestAward =NULL;
    private $mInvestTicket =NULL;
    static public function instance()
    {
        if (self::$self == NULL) {
            self::$self = new self;
        }
        return self::$self;
    }


    public function __construct()
    {
        $this->mInvest               =   new Involved_InvestModel();
        $this->mDealRecord           =   new Involved_DealRecordModel();
        $this->mUser = new Involved_UserModel();
        $this->mUserAward = new Involved_UserAwardModel();
        $this->mItem = new Involved_ItemModel();
        $this->mUserTicket = new Involved_UserTicketModel();
        $this->mExperItem = new Involved_ExperItemModel();
        $this->mExperRecord = new Involved_ExperRecordModel();
        $this->mUserFund = new Involved_UserFundModel();
        $this->mInvestAward = new Involved_InvestAwardModel();
        $this->mInvestTicket = new Involved_InvestTicketModel();

    }



        public function Iscard($paramObj){
                return $this->mUser->Iscard($paramObj);

        }



    /**
     * 用户中心投资记录
     * @param $user_id
     * @return mixed
     */
    public function UserAccountsInvestment($user_id,$page,$page_size)
    {
        return $this->mInvest->UserAccountsInvestment($user_id,$page,$page_size);
    }

    /**
     * 检索最优红包
     */
    public function SelectAward($paramObj){
        return $this->mUserAward->SelectAward($paramObj);
    }
    /**
     * 检索30天可用红包
     */
    public function Thirty($paramObj){
        return $this->mUserAward->Thirty($paramObj);
    }
    /**
     * 检索60天可用红包
     */
    public function Sixty($paramObj){
        return $this->mUserAward->Sixty($paramObj);
    }
    /**
     * ////
     */
    public function Sixtys($paramObj){
        return $this->mUserAward->Sixty($paramObj);
    }
    /**
     * 检索60天以上可用红包
     */
    public function Much($paramObj){
        return $this->mUserAward->Much($paramObj);
    }
    /**
     * 检索可用加息券
     */
    public function SelectTicket($paramObj){
        return $this->mUserTicket->SelectTicket($paramObj);
    }

    /**
     * 投资记录条数查询
     * @param $user_id
     * @return mixed
     */
    public function InvestCount($user_id)
    {
        return $this->mInvest->InvestCount($user_id);
    }


    /**
     * 投资记录条数条件查询
     * @param $user_id
     * @param $begin_time
     * @param $end_time
     * @return mixed
     */
    public function InvestSelCount($user_id,$begin_time,$end_time)
    {

        return $this->mInvest->InvestSelCount($user_id,$begin_time,$end_time);

    }

    /**
     * 投资记录数据条件查询
     * @param $user_id
     * @param $page
     * @param $page_size
     * @param $begin_time
     * @param $end_time
     * @return mixed
     */
    public function UserInvestSel($user_id,$page,$page_size,$begin_time,$end_time)
    {

        return $this->mInvest->UserInvestSel($user_id,$page,$page_size,$begin_time,$end_time);
    }



    /**
     * API确认投资
     */
    public function Confirminvest($paramObj){
        // 检查加息券是否存在
        /* if ($ticketID)
         {
             $UTTable = table('user\\Ticket');
             $ticketWhere = ['user_id' => $this->_user['user_id'], 'auto_id' => $ticketID];
             $ticket = $UTTable->where($ticketWhere)->find();

             if (!$ticket)
             {
                 return $this->returned(400, '您选择的加息券不存在');
             }
         }*/


        // 如果是ajax 直接返回检查成功
        /* if ($this->request->isAjax())
         {
             return $this->jsonReturn(200, 'OK');
         }

         // 检查是够存在红包
         $awardTable = table('user\\Award');
         $awardWhere = [
             'user_id' => $this->_user['user_id'],
             'status'  => 'AVAILABLE'
         ];
         $awards = $awardTable->where($awardWhere)->order('amount desc')->field('auto_id,amount,restrict_amount')->query();

         // 是否存在可用红包
         $award  = [];
         foreach ($awards as $key => $value)
         {
             if ($amountCent >= $value['restrict_amount'])
             {
                 $award = $value;
                 break;
             }
         }*/
        // 创建订单号
        $tradeNum = StatusEnum::buildNumber('INVEST');

        if (!$tradeNum)
        {
            return '订单号创建失败，请稍后再试';
        }
        // 构建一张支付订单
        $trade = [
            // 订单号码
            'trade_num'=> $tradeNum,
            // 用户ID
            'user_id'  => $paramObj->user_id,
            'item_id'  => $paramObj->item_id,
            //年化利率
            'rate'     =>$paramObj->rate,
            //红包ID
            'award_id'     =>$paramObj->award_id,
            //加息券ID
            'ticket_id'     =>$paramObj->ticket_id,
            //站岗金额
            'subsidy'     => 0,
            //站岗天数
            'subsidy_day'     => 0,
            // 订单金额, 分为单位
            'amount'   => $paramObj->amount,
            // 订单状态
            'status'   => 'WAIT',
            // 创建时间
            'add_time' => time(),
        ];
        return $this->mInvest->insert($trade);



    }

    /**
     * 投资成功操作
     */
    public  function success($tradeNum)
    {
        // 查找投资订单
        $investWhere = [
            'trade_num' => $tradeNum,
            'status'    => 'WAIT',
        ];
        $trade =  $this->mInvest->InvestTradeNum($investWhere);
        if (!$trade)
        {
            return "投资订单不存在";
        }
        // 余额扣除
        DealService::instance()->carry(
        // 用户ID
            $trade->user_id,
            // 操作总资金
            -$trade->amount,
            // 事件ID
            $trade->auto_id,
            // 交易类型:投资
            'DE_INVEST',
            // 交易资金明细
            ['MONEY_DEPOSIT' => -$trade->amount, 'MONEY_FREEZE' => $trade->amount],
            // 业务说明:投标
            'INVEST'
        );

        // 修改投资订单状态为投资成功
        // DB::table('invest')->where('trade_num', $tradeNum)->update('status', 'SUCCESS');
        $this->mInvest->UpdateSuccess($tradeNum);
        // 更新项目可投金额
        $item =  $this->mItem->IsItem($trade->item_id);

        // 如果满标, 更新标的为募集完成状态
        if ($item->amount <= ($item->amount_collect + $trade->amount))
        {
            $this->mItem->UpdateAmount($trade->item_id,$trade->amount);
            $this->mItem->UpdateReady($trade->item_id);
            //DB::table('item')->where('auto_id', $trade->item_id)->update($stre);
        }
        // 未满标, 更新投资金额
        else
        {
            //DB::table('item')->UpdateAmount('amount_collect', $trade->amount);
            $this->mItem->UpdateAmount($trade->item_id,$trade->amount);
        }

        // 是否使用了红包, 如果使用过则激活
        if ($trade->award_id)
        {
            $updateAward = [
                'status'    => 'HAS_USED',
                'trade_num' => $tradeNum,
            ];
            DB::table('user_award')->where(['auto_id' => $trade->award_id, 'status' => 'AVAILABLE'])->update($updateAward);
            //查询加息券单挑记录
            $invest_awrad = $this->mUserAward->FindAward($trade->award_id);
            //插入加息券记录
            $invest_array=[
                'user_id'    => $trade->user_id,
                'item_id' =>  $trade->item_id,
                'award_id'=>$invest_awrad->auto_id,
                'amount'=>$invest_awrad->amount,
                'add_time'=>time()

            ];
            $this->mInvestAward->insert($invest_array);

            //插入红包记录
        }
        // 是否使用了加息券, 如果使用过则激活
        if ($trade->ticket_id)
        {
            $updateTicket = [
                'status'    => 'IN_USE',
                'trade_num' => $tradeNum,
            ];
            DB::table('user_ticket')->where(['auto_id' => $trade->ticket_id, 'status' => 'AVAILABLE'])->update($updateTicket);
            //查询加息券单挑记录
            $invest_ticket = $this->mUserTicket->FindTicket($trade->ticket_id);
            //插入加息券记录
            $invest_array=[
                'user_id'    => $trade->user_id,
                'item_id' =>  $trade->item_id,
                'ticket_id'=>$invest_ticket->auto_id,
                'rate'=>$invest_ticket->rate,
                'add_time'=>time()

            ];
            $this->mInvestTicket->insert($invest_array);

        }
        // 站内信通知
        UserService::instance()->send(
            $trade->user_id,
            '投标成功通知',
           '尊敬的用户，您已成功投资 '.number_format($trade->amount/100, 2).' 元，详情请到投资记录查看'
        );
        $result=[
            'amount'      => number_format($trade->amount/100, 2),
            'code' => 200,
        ];
        return $result;
    }
    public  function SelectInvest($trade_id){
        return $this->mInvest->SelectInvest($trade_id);
    }



















    /**
     * 资金流水充值默认查询
     * @param $user_id
     * @return mixed
     */
    public function UserAccountsCapitalflow($user_id,$page,$page_size)
    {
        return $this->mDealRecord->UserAccountsCapitalflow($user_id,$page,$page_size);
    }

    /**
     * 资金流水条数充值默认查询
     * @param $user_id
     * @return mixed
     */
    public function CapitalCount($user_id)
    {
        return $this->mDealRecord->CapitalCount($user_id);
    }


    /**
     * 资金流水精确条数查询
     * @param $user_id
     * @param $paramObj
     * @return mixed
     */
    public function CapitalExactCount($user_id,$paramObj)
    {
        return $this->mDealRecord->CapitalExactCount($user_id,$paramObj);
    }

    /**
     * 资金流水精确查询
     * @param $user_id
     * @param $paramObj
     * @return mixed
     */
    public function CapitalExactSel($user_id,$paramObj,$page,$page_size)
    {
        return $this->mDealRecord->CapitalExactSel($user_id,$paramObj,$page,$page_size);
    }

    /**
     * 资金流水范围条数查询
     * @param $user_id
     * @param $paramObj
     * @return mixed
     */
    public  function CapitalRangeCount($user_id,$paramObj)
    {
        return $this->mDealRecord->CapitalRangeCount($user_id,$paramObj);
    }

    /**
     * 资金流水范围查询
     * @param $user_id
     * @param $paramObj
     * @return mixed
     */
    public function CapitalRangeSel($user_id,$paramObj,$page,$page_size)
    {
        return $this->mDealRecord->CapitalRangeSel($user_id,$paramObj,$page,$page_size);
    }
    /**
     * 检查该用户是否投资过该标
     */
    public function IsInvest($item_id,$user_id){
        return $this->mInvest->IsInvest($item_id,$user_id);
    }


    /**
     * 体验标详情
     * @return mixed
     */
    public function Tiyan()
    {
        return $this->mExperItem->Tiyan();
    }

    /**
     * Api体验标详情
     * @return mixed
     */
    public function ApiTiyan()
    {
        return $this->mExperItem->ApiTiyan();
    }

    /**
     * 体验标投资查询
     * @param $exper_id
     * @param $user_id
     * @return mixed
     */
    public function ExperInvest($exper_id,$user_id)
    {
        return DB::table('exper_record')->where('exper_id',$exper_id)->where('user_id',$user_id)->get();

    }

    /**
     * 体验金投资记录
     * @param $exper_id
     * @param $user_id
     * @param $exper_amount
     * @return mixed
     */
    public function ExperInsert($exper_id,$user_id,$exper_amount)
    {
        // 创建订单号
        $tradeNum = StatusEnum::buildNumber('EXPER_MONEY');

        if (!$tradeNum)
        {
            return '订单号创建失败，请稍后再试';
        }
        // 构建一张支付订单
        $trade = [
            // 订单号码
            'trade_num'=> $tradeNum,
            // 用户ID
            'user_id'  => $user_id,
            'exper_id'  => $exper_id,
            //体验金金额
            'exper_amount'  => $exper_amount,
            //年化利率
            'rate'     =>10,
            // 订单状态
            'status'   => 'WAIT',
            // 创建时间
            'exper_time' => time(),
            //汇款金额
            'return_money' => number_format($exper_amount*0.1/365,2)*100
        ];
        return $this->mExperRecord->insert($trade);
//        return DB::table('exper_record')->insert(array(
//            array('user_id' => $user_id, 'exper_id' =>$exper_id,'exper_amount'=>$exper_amount,'exper_time'=>time()),
//        ));
    }

    /**
     * 融资金额
     * @param $exper_id
     * @return mixed
     */
    public function ExperAllAmount($exper_id)
    {
        return DB::table('exper_record')->where('exper_id',$exper_id)->whereBetween('exper_time',array(strtotime(date('Y-m-d', time())),strtotime(date('Y-m-d', time()))+86400))->get();
    }

    /**
     * 融资金额
     * @param $exper_id
     * @return mixed
     */
    public function ExperAllAmountNum($exper_id,$amount)
    {
        $exper_amount = DB::table('exper_record')->where('exper_id',$exper_id)->whereBetween('exper_time',array(strtotime(date('Y-m-d', time())),strtotime(date('Y-m-d', time()))+86400))->sum('exper_amount');
        return number_format($amount-$exper_amount);
    }

    /**
     * 体验标前一天用户id查询
     * @return mixed
     */
    public function ExperInvestSel()
    {
        return $this->mExperRecord->ExperInvestSel();
    }

    /**
     * 体验标返现
     * @param $arr
     * @return string
     */
    public function FundMoneyReturn($arr)
    {
        $money_return =  DB::table('exper_record')->whereIn('user_id',$arr)->get();
        foreach($money_return as $k=>$v){
            // 查找投资订单
            $investWhere = [
                'trade_num' => $v->trade_num,
                'status'    => 'WAIT',
            ];
            $trade =  DB::table('exper_record')->where($investWhere)->first();
            if (!$trade)
            {
                return "投资订单不存在";
            }
            // 余额扣除
            $aa = DealService::instance()->carry(
            // 用户ID
                $trade->user_id,
                // 操作总资金
                $trade->return_money,
                // 事件ID
                $trade->auto_id,
                // 交易类型:投资
                'IN_EXPER',
                // 交易资金明细
                ['MONEY_DEPOSIT' => $trade->return_money,'MONEY_FREEZE' => 0],
                // 业务说明:投标
                'EXPER_MONEY'

            );
            if($aa == 200){
                $aData2 = [
                    'status' => 'SUCCESS',
                ];
                $this->mExperRecord->update($aData2,['user_id'=>$v->user_id]);
            }
        }
    }







}